const MAX_LIMIT = 10
const db = wx.cloud.database()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        blogList: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this._getListByCloudFn()
        // this._getListByMiniprogram()
    },

    // 获取列表：调用云函数，由云函数读取数据库
    _getListByCloudFn() {
        wx.showLoading({
            title: '加载中',
        })
        wx.cloud.callFunction({
            name: 'blog',
            data: {
                $url: 'getListByOpenid',
                start: this.data.blogList.length,
                count: MAX_LIMIT
            }
        }).then((res) => {
            this.setData({
                blogList: this.data.blogList.concat(res.result)
            })
            wx.hideLoading()
        })
    },

    // 获取列表：小程序端直接读取数据库
    _getListByMiniprogram() {
        wx.showLoading({
            title: '加载中',
        })
        db.collection('blog').skip(this.data.blogList.length)
            .limit(MAX_LIMIT).orderBy('createTime', 'desc').get().then((res) => {
                let _bloglist = res.data
                for (let i = 0, len = _bloglist.length; i < len; i++) {
                    _bloglist[i].createTime = _bloglist[i].createTime.toString()
                }

                this.setData({
                    blogList: this.data.blogList.concat(_bloglist)
                })

                wx.hideLoading()
            })
    },

    // 跳转到详情页
    goDetail(event) {
        wx.navigateTo({
            url: `../blog-detail/blog-detail?blogId=${event.target.dataset.blogid}`,
        })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this._getListByCloudFn()
        // this._getListByMiniprogram()
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(event) {
        const blog = event.target.dataset.blog
        return {
            title: blog.content,
            path: `/pages/blog-detail/blog-detail?blogId=${blog._id}`
        }
    }
})